import service from 'axios'
import { ACCESS_TOKEN, CODE_SUCCESS, REFRESH_TOKEN } from './constant'
import router from '../router/index'
import {baseURL} from './request'

let subscribers:any = []
let pending = false //同时请求多个过期链接，保证只请求一次获取短token
/**
 * 保存出错请求
 * @param {*} request 
 */
export const addSubscriber = (request:any) => {
	subscribers.push(request)
}
/**
 * 恢复重新执行上次出错资源请求
 */
export const retryRequest = () => {
	subscribers.forEach((request:any) => {
		request()
	})
	subscribers = []
}
/**
 * 刷新accessToken
 * accessToken失效，重新请求
 * @returns 
 */
export const refreshAccessToken = async () => {
    // pending防止重复刷新,房卡生效需要时间，在这个时间内不允许重复刷新
	console.log('refreshAccessToken pending ',pending);
	
	if (!pending) {
		try {
			pending = true
			const l_tk = localStorage.getItem(REFRESH_TOKEN)
			if (l_tk) {
				/* 重新获取短token */
				const res = await service.get(baseURL+'/api/refresh?longToken=' + l_tk)
				const {resultCode,resultInfo,token} = res.data

				if(resultCode === CODE_SUCCESS ){
					localStorage.setItem(ACCESS_TOKEN, token)
					retryRequest()//自动请求保存的上次出错资源请求
				}else{
					clearAuthAndRedirect()
				}
				
			}
			return
		} catch (e) {
			clearAuthAndRedirect()
			console.log('e ',e);
			return
		} finally {
			pending = false
		}
	}
}

/* 清除长短token，并定位到登录页（在项目中使用路由跳转） */
export const clearAuthAndRedirect = () => {
	localStorage.removeItem(ACCESS_TOKEN)
	localStorage.removeItem(REFRESH_TOKEN)
	router.replace('/login')
}
